<template>
  <el-card>
    <div slot="header">
      <!-- 日期选择 -->
      <el-date-picker value-format="yyyy-MM-dd HH:mm:ss" format="yyyy-MM-dd HH:mm:ss" size="small" v-model="date" type="datetimerange" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期"> </el-date-picker>

      <el-button @click="search" type="primary" size="small">查询</el-button>
    </div>

    <div class="content">
      <!-- 内容 -->
      <div id="lineChart" style="height: 400px"></div>
    </div>
  </el-card>
</template>

<script>
import * as echarts from 'echarts'
import { getOrderChartsData } from '@/api/order'
import { formatDatenyrsfm } from '@/filters'

export default {
  data() {
    return {
      date: []
    }
  },
  methods: {
    // 绘制折线图
    drawLine(xData, yData) {
      this.lineCharts = echarts.init(document.querySelector('#lineChart'))

      const option = {
        tooltip: {
          trigger: 'axis'
        },
        xAxis: {
          type: 'category',
          data: xData
        },
        yAxis: {
          type: 'value'
        },
        series: [
          {
            data: yData,
            type: 'line'
          }
        ]
      }

      this.lineCharts.setOption(option)
    },

    // 适配echarts方法
    resize() {
      this.lineCharts.resize() // 调用resize方法适配
    },

    // 获取数据 渲染echarts
    async getDataRenderCharts() {
      // 让清除时间之后  date依然是 [] 而不是null
      this.date = this.date == null ? [] : this.date

      let res = await getOrderChartsData({ date: JSON.stringify(this.date) })
      // 把时间取出来 当成x轴  把金额取出来 当成y轴
      let xData = res.data.data.map(v => formatDatenyrsfm(v.orderTime))
      let yData = res.data.data.map(v => v.orderAmount)
      // 传入ajax获取到的动态数据 渲染echarts
      this.drawLine(xData, yData)
    },

    // 查询
    search() {
      // 调用方法 后去数据 渲染报表
      this.getDataRenderCharts()
    }
  },
  mounted() {
    // 调用方法 后去数据 渲染报表
    this.getDataRenderCharts()

    // 适配
    window.addEventListener('resize', this.resize)
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.resize)
  }
}
</script>

<style lang="less" scoped>
.el-button {
  margin-left: 20px;
}
</style>
